package com.billjc.activity.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.ObjectPool;
import org.springframework.util.Assert;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FtpUtil {
	/**
	 * ftpClient连接池初始化标志
	 */
	private static volatile boolean eformHasInit = false;
	
	private static volatile boolean imageHasInit = false;
	/**
	 * ftpClient连接池
	 */
	private static ObjectPool<FTPClient> eformFtpClientPool;
	
	private static ObjectPool<FTPClient> imageFtpClientPool;
	/**
	 * 初始化ftp连接池
	 * @param ftpClientPool
	 */
	public static void initEformPool(ObjectPool<FTPClient> eformFtpClientPool) {
		if(!eformHasInit) {
			synchronized (FtpUtil.class) {
				if (!eformHasInit) {
                    FtpUtil.eformFtpClientPool = eformFtpClientPool;
                    eformHasInit = true;
                }
			}
		}
	}
	
	public static void initImagePool(ObjectPool<FTPClient> imageFtpClientPool) {
		if(!imageHasInit) {
			synchronized (FtpUtil.class) {
				if (!imageHasInit) {
                    FtpUtil.imageFtpClientPool = imageFtpClientPool;
                    imageHasInit = true;
                }
			}
		}
	}
	/**
	 * 获取ftp连接
	 * @return
	 */
	 private static FTPClient getFtpClient(String type) {
		 checkFtpClientPoolAvailable();
	        FTPClient ftpClient = null;
	        Exception ex = null;
	        // 获取连接最多尝试3次
	        for (int i = 0; i < 3; i++) {
	            try {
	            	if(StringUtils.equals("eform", type)) {
	            		 ftpClient = eformFtpClientPool.borrowObject();
	            	}else {
	            		 ftpClient = imageFtpClientPool.borrowObject();
	            	}
	                ftpClient.changeWorkingDirectory("/");
	                break;
	            } catch (Exception e) {
	                ex = e;
	            }
	        }
	        if (ftpClient == null) {
	            throw new RuntimeException("Could not get a ftpClient from the eformFtpClientPool", ex);
	        }
	        return ftpClient;
	 }
	 private static void checkFtpClientPoolAvailable() {
		 Assert.state(eformHasInit, "FTP未启用或连接失败！");
	 }

	/**
	 * 释放ftpClient
	 */
	private static void releaseFtpClient(FTPClient ftpClient,String type) {
		if (ftpClient == null) {
			return;
		}

		try {
			if(StringUtils.equals("eform", type)) {
				eformFtpClientPool.returnObject(ftpClient);	
			}else {
				imageFtpClientPool.returnObject(ftpClient);
			}
		} catch (Exception e) {
			log.error("Could not return the ftpClient to the pool", e);
			// destoryFtpClient
			if (ftpClient.isAvailable()) {
				try {
					ftpClient.disconnect();
				} catch (IOException io) {
				}
			}
		}
	}

	/**
	 * 下载指定路径下的文件到某个路径下
	 * 
	 * @param remotePath
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static void downLoadFile(String remotePath,String relativeLocalPath) throws UnsupportedEncodingException, IOException {
		FTPClient ftpClient = getFtpClient("eform");
		File entryDir = null;
		OutputStream output = null;  
		try {
			entryDir = new File(relativeLocalPath);
			if(!entryDir.exists() || !entryDir.isDirectory()) {
				entryDir.mkdirs();
			}
			String localName = "/"+remotePath.split("/")[2];
			File localFile = new File(relativeLocalPath+localName);
			if(localFile.exists()) {
				return;
			}else {
				output = new FileOutputStream(relativeLocalPath+ localName); 
				ftpClient.retrieveFile(remotePath, output); 
				output.flush(); 
				output.close(); 
			}
		} finally {
			releaseFtpClient(ftpClient,"eform");
		}
	}
	/**
	 * ftp上传文件
	 * @param fileName
	 * @param fileLocalPath
	 * @return
	 * @throws IOException
	 */
	public static boolean uploadFile(String fileLocalPath) throws IOException {
		FTPClient ftpClient = getFtpClient("iamge");
		File localFile = new File(fileLocalPath);
		BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(localFile));
		try {
			ftpClient.enterLocalPassiveMode();
			ftpClient.setFileType(2);
			ftpClient.makeDirectory("/activityTest");
			ftpClient.changeWorkingDirectory("/activityTest");
			Boolean flag = ftpClient.storeFile(localFile.getName(), inStream);
			log.debug("文件: "+localFile.getName()+",上传状态--->"+String.valueOf(flag));
		} finally {
			//ftpClient.completePendingCommand();
			releaseFtpClient(ftpClient,"image");
		}
		return false;
	}

	/**
     * 编码文件路径
     */
    private static String encodingPath(String path) throws UnsupportedEncodingException {
        // FTP协议里面，规定文件名编码为iso-8859-1，所以目录名或文件名需要转码
        return new String(path.replaceAll("//", "/").getBytes("GBK"), "iso-8859-1");
    }
}
